package com.robinmouren.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.robinmouren.constant.AutoFillConstant;
import com.robinmouren.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义元数据对象处理器
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入操作，自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");

        if (metaObject.hasGetter(AutoFillConstant.CREATE_TIME)) {
            metaObject.setValue(AutoFillConstant.CREATE_TIME, LocalDateTime.now());
        }

        if (metaObject.hasGetter(AutoFillConstant.UPDATE_TIME)) {
            metaObject.setValue(AutoFillConstant.UPDATE_TIME, LocalDateTime.now());
        }

        if (metaObject.hasGetter(AutoFillConstant.CREATE_USER)) {
            metaObject.setValue(AutoFillConstant.CREATE_USER, BaseContext.getCurrentId());
        }
        if (metaObject.hasGetter(AutoFillConstant.UPDATE_USER)) {
            metaObject.setValue(AutoFillConstant.UPDATE_USER, BaseContext.getCurrentId());
        }
    }

    /**
     * 修改操作，自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...{}", metaObject.toString());

        metaObject.setValue(AutoFillConstant.UPDATE_TIME, LocalDateTime.now());
        // 修改字段时若id为空则本次不修改id
        if(BaseContext.getCurrentId() != null){
            metaObject.setValue(AutoFillConstant.UPDATE_USER, BaseContext.getCurrentId());
        }
    }

}
